﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.IO;
using System.Threading;
using System.Diagnostics;

namespace SQLComparer
{
    public partial class FormMain : Form
    {
        public static EventHandler LoadedData;

        public FormMain()
        {
            InitializeComponent();
            LoadedData = ON_LoadedData;
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void ON_LoadedData(object sender, EventArgs e)
        {
            Disable(true);
            RefreshData();
        }
        private void Disable(bool Enable)
        {
            this.toolStrip1.Enabled = Enable;
            //this.button1.Enabled =
            //    this.checkBox1.Enabled =
            //    this.checkBox2.Enabled =
            //    this.checkBox3.Enabled =
            //    this.checkBox4.Enabled =
            //    this.button2.Enabled = Enable;
        }

        private void RefreshData()
        {
            string filter = string.Empty;
            if (this.tableToolStripMenuItem.Checked)
            {
                filter += tableToolStripMenuItem.Tag.ToString() + ";";
            }
            if (this.storedProcedureToolStripMenuItem.Checked)
            {
                filter += storedProcedureToolStripMenuItem.Tag.ToString() + ";";
            }
            if (this.viewToolStripMenuItem.Checked)
            {
                filter += viewToolStripMenuItem.Tag.ToString() + ";";
            }
            if (this.functionToolStripMenuItem.Checked)
            {
                filter += functionToolStripMenuItem.Tag.ToString() + ";";
            }


            List<Different> list = new List<Different>();
            List<Exclude> exList = Exclude.Deserialize();
            foreach (Different d in DBManager.tableDictionary.Values)
            {
                if ((d.TypeA == null || filter.Contains(d.TypeA)) && (d.TypeB == null || filter.Contains(d.TypeB)))
                {
                    bool exclude = false;
                    foreach (Exclude ex in exList)
                    {
                        if ((ex.Type == d.TypeA && ex.Schema == d.SchemaA && ex.Name == d.NameA) ||
                             (ex.Type == d.TypeB && ex.Schema == d.SchemaB && ex.Name == d.NameB))
                        {
                            exclude = true;
                            break;
                        }
                    }
                    if (exclude == false)
                    {
                        switch (this.toolStripDifferent.Tag.ToString())
                        {
                            case "left":
                                if (string.IsNullOrEmpty(d.NameA))
                                {
                                    list.Add(d);
                                }
                                break;
                            case "right":
                                if (string.IsNullOrEmpty(d.NameB))
                                {
                                    list.Add(d);
                                }
                                break;
                            case "both":
                                if (string.IsNullOrEmpty(d.NameA) || string.IsNullOrEmpty(d.NameB))
                                {
                                    list.Add(d);
                                }
                                break;
                            case "same":
                                if (d.NameA == d.NameB)
                                {
                                    list.Add(d);
                                }
                                break;
                            default:
                                list.Add(d);
                                break;
                        }
                    }
                }
            }
            //this.dataGridView1.DataSource = null;
            this.dataGridView1.DataSource = list;
            this.toolStripLabel1.Text = string.Format("{0}条记录", list.Count);
            this.toolStripLabel1.Alignment = ToolStripItemAlignment.Right;
            foreach (DataGridViewRow dr in dataGridView1.Rows)
            {
                bool same;
                if (dr.Cells["ScriptA"].Value == null && dr.Cells["ScriptB"].Value == null)
                {
                    DataGridViewCellStyle StyleChanged = new DataGridViewCellStyle();
                    StyleChanged.ForeColor = Color.Black;
                    dr.DefaultCellStyle = new DataGridViewCellStyle(StyleChanged);
                }
                else
                {
                    if (dr.Cells["ScriptA"].Value != null && dr.Cells["ScriptB"].Value != null)
                    {
                        same = (dr.Cells["ScriptA"].Value.ToString().Equals(dr.Cells["ScriptB"].Value.ToString(), StringComparison.CurrentCultureIgnoreCase));
                    }
                    else
                    {
                        same = false;
                    }
                    if (same)
                    {
                        DataGridViewCellStyle StyleChanged = new DataGridViewCellStyle();
                        StyleChanged.ForeColor = Color.Blue;
                        dr.DefaultCellStyle = new DataGridViewCellStyle(StyleChanged);
                    }
                    else
                    {
                        DataGridViewCellStyle StyleChanged = new DataGridViewCellStyle();
                        StyleChanged.ForeColor = Color.Red;
                        dr.DefaultCellStyle = new DataGridViewCellStyle(StyleChanged);
                    }
                }
            }
        }

        private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                List<Exclude> list = Exclude.Deserialize();
                foreach (DataGridViewRow dr in this.dataGridView1.SelectedRows)
                {
                    Exclude ex = new Exclude();
                    if (dr.Cells["NameA"].Value != null)
                    {
                        ex.Name = dr.Cells["NameA"].Value.ToString();
                        ex.Schema = dr.Cells["SchemaA"].Value.ToString();
                        ex.Type = dr.Cells["TypeA"].Value.ToString();
                    }
                    else
                    {
                        ex.Name = dr.Cells["NameB"].Value.ToString();
                        ex.Schema = dr.Cells["SchemaB"].Value.ToString();
                        ex.Type = dr.Cells["TypeB"].Value.ToString();
                    }
                    bool exists = false;
                    foreach (Exclude eeee in list)
                    {
                        if (eeee.Schema + eeee.Type + eeee.Name == ex.Schema + ex.Type + ex.Name)
                        {
                            exists = true;
                            break;
                        }
                    }
                    if (exists == false)
                    {
                        list.Add(ex);
                    }
                }
                Exclude.Serialize(list);
                RefreshData();
            }
            if (e.KeyCode == Keys.Enter)
            {
                this.toolStripCompare_Click(sender, e);
            }
        }

        #region like database

        private void toolStripLink_Click(object sender, EventArgs e)
        {
            this.dataGridView1.DataSource = null;
            FormConnection f = new FormConnection();

            if (f.ShowDialog() == DialogResult.Yes)
            {
                DBManager DBManagment = new DBManager();
                ThreadStart ts = DBManagment.LoadData;
                Thread thread = new Thread(ts);
                Disable(false);
                thread.Start();
            }
        }

        private void toolStripSwap_Click(object sender, EventArgs e)
        {
            this.dataGridView1.DataSource = null;
            Connection temp = new Connection();

            temp = DBManager.ConnectionA;
            DBManager.ConnectionA = DBManager.ConnectionB;
            DBManager.ConnectionB = temp;

            DBManager DBManagment = new DBManager();

            ThreadStart ts = DBManagment.LoadData;
            Thread thread = new Thread(ts);
            Disable(false);
            thread.Start();
        }

        #endregion


        #region Filter data

        private void toolStripFilter_Click(object sender, EventArgs e)
        {
            new FormExclude().ShowDialog();
            RefreshData();
        }

        private void allToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.toolStripDifferent.Image = this.allToolStripMenuItem.Image;
            this.toolStripDifferent.Tag = "all";
            RefreshData();
        }

        private void leftToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.toolStripDifferent.Image = this.leftToolStripMenuItem.Image;
            this.toolStripDifferent.Tag = "left";
            RefreshData();
        }

        private void rightToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.toolStripDifferent.Image = this.rightToolStripMenuItem.Image;
            this.toolStripDifferent.Tag = "right";
            RefreshData();
        }

        private void bothToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.toolStripDifferent.Image = this.bothToolStripMenuItem.Image;
            this.toolStripDifferent.Tag = "both";
            RefreshData();
        }

        private void sameToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.toolStripDifferent.Image = this.sameToolStripMenuItem.Image;
            this.toolStripDifferent.Tag = "same";
            RefreshData();
        }

        private void toolStripType_Click(object sender, EventArgs e)
        {
            RefreshData();
        }
        #endregion

        private void toolStripCompare_Click(object sender, EventArgs e)
        {
            string ScriptA = string.Empty;
            string ScriptB = string.Empty;

            if (this.dataGridView1.SelectedRows.Count > 0)
            {

                foreach (DataGridViewRow dr in dataGridView1.SelectedRows)
                {

                    if (dr.Cells["ScriptA"].Value != null)
                    {
                        ScriptA += dr.Cells["ScriptA"].Value.ToString();
                    }
                    ScriptA += "\r\n";
                    if (dr.Cells["ScriptB"].Value != null)
                    {
                        ScriptB += dr.Cells["ScriptB"].Value.ToString();
                    }
                    ScriptB += "\r\n";
                }

            }
            else
            {
                foreach (DataGridViewRow dr in dataGridView1.Rows)
                {
                    if (dr.Cells["ScriptA"].Value != null)
                    {
                        ScriptA += dr.Cells["ScriptA"].Value.ToString();
                    }
                    ScriptA += "\r\n";
                    if (dr.Cells["ScriptB"].Value != null)
                    {
                        ScriptB += dr.Cells["ScriptB"].Value.ToString();
                    }
                    ScriptB += "\r\n";
                }
            }
            File.WriteAllText(Application.StartupPath + "\\ScriptA.sql", ScriptA);
            File.WriteAllText(Application.StartupPath + "\\ScriptB.sql ", ScriptB);
            string p = string.Format(" \"{0}\"  \"{1}\" ", Application.StartupPath + "\\ScriptA.sql", Application.StartupPath + "\\ScriptB.sql");
            Process.Start(Application.StartupPath + "\\Comparer", p);
        }

        private void FormMain_Load(object sender, EventArgs e)
        {

        }


    }
}